import { Grid, useDisclosure } from '@chakra-ui/react';
import {
  setCurrentSub,
  setTagMap,
  setTagSub,
} from 'features/tag/store/tagSlice';
import Sub from 'features/tag/components/Sub/Sub';
import {
  SubCategory,
  TagSubItem,
} from 'features/tag/components/Sub/SubContent';
import TagDisplayBox from 'features/tag/components/TagDisplayBox';
// import DefaultHeader from 'common/components/DefaultHeader';
import { useEffect } from 'react';
import { useAppDispatch } from 'app/store/storeHooks';

import tagJson from '../tags-data/tag.json';
import SelectedPromptTags from './SelectedPromptTags';
import { TagType } from './TagDisplayBox/TagDisplayItemCard';
export interface Tag {
  key: string;
  alias: string[] | null;
  name: string;
  category: string[];
  description: string | null;
  image: string | null;
  wikiURL: string | null;
  restricted: boolean | null;
}

export interface TagFileItem {
  name: string;
  description: string | null;
  image: string | null;
  wikiURL: string | null;
  alias: string[] | null;
  restricted: boolean | null;
}

export interface TagFile {
  name: string;
  category: string[];
  restricted: boolean | null;
  content: Record<string, TagFileItem>;
}
const isSubCategory = (item: TagSubItem): item is SubCategory => {
  return (item as SubCategory).subs !== undefined;
};

const loadTags = async (cb?: (sub: any) => void) => {
  const sub: Record<string, TagSubItem> = tagJson;

  const tagMap: Record<string, TagType[]> = {};

  Object.values(sub).forEach((t) => {
    if (isSubCategory(t)) {
      t.subs.forEach((i) => {
        tagMap[i.name as keyof typeof tagMap] = i.tags || [];
      });
    } else {
      tagMap[t.name] = t.tags || [];
    }
  });

  cb && cb({ sub, tagMap });
};

const PromptTags = () => {
  const dispatch = useAppDispatch();
  const { isOpen, onClose, onOpen } = useDisclosure();
  useEffect(() => {
    loadTags(({ sub, tagMap }) => {
      const subList: TagSubItem[] = Object.values(sub);
      dispatch(setTagSub(subList));
      dispatch(setTagMap(tagMap));
      dispatch(setCurrentSub(Object.keys(tagMap)[0]));
    });
  }, [dispatch]);
  return (
    <Grid
      gridTemplateAreas={{
        base: `'selected'
          'tags'`,
        md: `'sub tags selected'`,
      }}
      gridTemplateColumns={{ base: '', md: '250px auto 350px' }}
      gridTemplateRows={{ base: '', md: 'calc(100vh - 40px - 3.5rem)' }}
    >
      <Sub subIsOpen={isOpen} subOnClose={onClose} />
      <TagDisplayBox subOnOpen={onOpen} />
      <SelectedPromptTags />
    </Grid>
  );
};
export default PromptTags;
